#include <bits/stdc++.h>
using namespace std;
#define yes cout << "YES" << endl
#define no cout << "NO" << endl
using ll = long long;
void solve()
{
    ll n;
    cin >> n;
    ll now = n, ans = 0;
    int x = 20;
    while (1)
    {
        if (pow(3, x) <= n)
        {
            n -= pow(3, x);
            ans += (9 + x) * pow(3, x - 1);
        }
        else
        {
            x--;
        }
        if (x < 0 || n == 0)
            break;
    }
    cout << ans << endl;
}
void solve_()
{
    ll n;
    cin >> n;
    ll ans = 0;
    for(ll bit=20;bit>=0;bit--)
    {
        int p=pow(3,bit);
        if(n>=p)
        {
            int cnt=n/p;
            int pir = pow(3, bit + 1);
            if(bit>=1)
                pir = pow(3, bit - 1)*bit;
            ans+=cnt*pir;
            n -= p * cnt;
        }
    }
    cout << ans << endl;
}
int main()
{
    int t = 1;
    cin >> t;
    while (t--)
    {
        solve();
    }
    return 0;
}
